package com.service.api;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.service.bean.signal.GpsSignal;
import com.service.other.Logger;

public class BaiduApiAddress extends BaiduApiServer {

	private GpsSignal bean;
	
	public BaiduApiAddress() {
		
	}
	
	
	public void getAddress(GpsSignal bean) {
		this.bean = bean;
		this.run();
	}
	
	@Override
	public void run() {
		try {
			StringBuilder builder = new StringBuilder();
			builder.append("http://api.map.baidu.com/geocoder/v2/?");
			builder.append("ak=x2QVIn5dDgDC7wRZ6WGoQykb");
			builder.append("&coordtype=bd09ll");
			builder.append("&pois=0");
			builder.append("&output=json");
			builder.append("&location=");
			builder.append(String.valueOf(bean.baiduLat));
			builder.append(",");
			builder.append(String.valueOf(bean.baiduLng));
			HttpClient client = new HttpClient();
			client.doRequest(builder.toString(), this);
		} catch (Exception e) {
			Logger.err(e);
		}
	}

	@Override
	public void callBack(String json) {
		String status = null;
		try {
			Pattern p = Pattern.compile("\"status\":\"?(?<status>\\S+?)\"?");
			Matcher m = p.matcher(json);
			if (m.find()) {
				status = m.group("status");
				if ("0".equals(status)) {
					this.bean.isLocation = 1;
					this.bean.isPosition = 1;
					p = Pattern.compile("\"formatted_address\":\"(?<address>\\S+?)\"");
					m = p.matcher(json);
					if(m.find()){
						this.bean.baiduLocation = m.group("address");
					}
					p = Pattern.compile("\"street\":\"(?<street>\\S+?)\"");
					m = p.matcher(json);
					if(m.find()){
						this.bean.baiduStreet = m.group("street");
					}
				}
			}
		} catch (Exception e) {
			Logger.err(e);
		}
	}
}
